<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px" size="small">
      <el-form-item label="" prop="activityName">
        <el-input
          v-model="queryParams.activityName"
          clearable
          placeholder="请输入活动名称"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="别名" prop="activityNickName">
              <el-input
                v-model="queryParams.activityNickName"
                placeholder="请输入别名"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>-->
      <!--      <el-form-item label="小程序显示" prop="appletShowEnable">
              <el-input
                v-model="queryParams.appletShowEnable"
                placeholder="请输入小程序显示"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>-->
      <!--      <el-form-item label="活动开始时间" prop="beginTime">
              <el-input
                v-model="queryParams.beginTime"
                placeholder="请输入活动开始时间"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>-->
      <!--      <el-form-item label="创建时间" prop="creatTime">
              <el-input
                v-model="queryParams.creatTime"
                placeholder="请输入创建时间"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>-->
      <!--      <el-form-item label="活动描述" prop="description">
              <el-input
                v-model="queryParams.description"
                placeholder="请输入活动描述"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>-->
      <!--      <el-form-item label="活动结束时间" prop="endTime">
              <el-input
                v-model="queryParams.endTime"
                placeholder="请输入活动结束时间"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>-->
      <!--      <el-form-item label="允许参与次数" prop="hitEnableCounts">
              <el-input
                v-model="queryParams.hitEnableCounts"
                placeholder="请输入允许参与次数"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>-->
      <!--      <el-form-item label="参与活动等级,执行不小于逻辑" prop="levelEnable">
              <el-input
                v-model="queryParams.levelEnable"
                placeholder="请输入参与活动等级,执行不小于逻辑"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="最多可选卡券数量,取值[1,最大有效关联卡券]" prop="maxChoose">
              <el-input
                v-model="queryParams.maxChoose"
                placeholder="请输入最多可选卡券数量,取值[1,最大有效关联卡券]"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>-->
      <el-form-item label="" prop="status">
        <el-select v-model="queryParams.status" clearable placeholder="请选择活动状态">
          <el-option
            v-for="dict in statusList"
            :key="dict.id"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="platformAgentId">
        <el-select v-model="queryParams.platformAgentId" clearable placeholder="请选择代理商">
          <el-option
            v-for="dict in agentList"
            :key="dict.id"
            :label="dict.agentName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="持续的0:不持续(限定时间)，1:持续的(不限定时间)" prop="sustained">
              <el-input
                v-model="queryParams.sustained"
                placeholder="请输入持续的0:不持续(限定时间)，1:持续的(不限定时间)"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>-->
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['activitys:commercialActivity:add']"
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          @click="handleAdd"
        >创建活动
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">
              <el-button
                v-hasPermi="['activitys:commercialActivity:edit']"
                :disabled="single"
                icon="el-icon-edit"
                plain
                size="mini"
                type="success"
                @click="handleUpdate"
              >修改
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                v-hasPermi="['activitys:commercialActivity:remove']"
                :disabled="multiple"
                icon="el-icon-delete"
                plain
                size="mini"
                type="danger"
                @click="handleDelete"
              >删除
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                v-hasPermi="['activitys:commercialActivity:export']"
                icon="el-icon-download"
                plain
                size="mini"
                type="warning"
                @click="handleExport"
              >导出
              </el-button>
            </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="commercialActivityList" @selection-change="handleSelectionChange">
      <el-table-column align="center" label="活动Id" prop="id"/>
      <el-table-column align="center" label="活动名称" prop="activityName"/>
      <el-table-column align="center" label="别名" prop="activityNickName"/>
      <el-table-column align="center" label="代理商" prop="platformAgentName"/>
      <el-table-column align="center" label="交互显示" prop="appletShowEnable"/>
      <!--   0:创建(未发布)1:发布(进行中)2:停止(暂停或结束)   -->
      <el-table-column align="center" label="活动状态" prop="status"/>
      <el-table-column align="center" label="参与次数" prop="hitEnableCounts"/>
      <!--  的0:不持续(限定时间)，1:持续的(不限定时间)    -->
      <el-table-column align="center" label="持续" prop="sustained"/>
      <!--      <el-table-column align="center" label="活动开始时间" prop="beginTime"/>
            <el-table-column align="center" label="创建时间" prop="creatTime"/>
            <el-table-column align="center" label="活动描述" prop="description"/>
            <el-table-column align="center" label="活动结束时间" prop="endTime"/>-->

      <!--      <el-table-column align="center" label="参与活动等级,执行不小于逻辑" prop="levelEnable"/>
            <el-table-column align="center" label="最多可选卡券数量,取值[1,最大有效关联卡券]" prop="maxChoose"/>-->


      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['activitys:commercialActivity:edit']"
            icon="el-icon-info"
            size="mini"
            type="text"
            @click="handleDetails(scope.row)"
          >详情
          </el-button>
          <el-button
            v-hasPermi="['activitys:commercialActivity:edit']"
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
          >设置
          </el-button>
          <el-button
            v-hasPermi="['activitys:commercialActivity:remove']"
            icon="el-icon-delete"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改商业活动对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="800px">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px"
               style="width: 100%;display: flex;justify-content: space-between;flex-wrap: wrap;">
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="form.activityName" placeholder="请输入活动名称" :disabled="detailsType"/>
        </el-form-item>
        <el-form-item label="别名" prop="activityNickName">
          <el-input v-model="form.activityNickName" placeholder="请输入别名" :disabled="detailsType"/>
        </el-form-item>
        <el-form-item label="交互显示" prop="appletShowEnable">
          <el-switch
            :disabled="detailsType"
            v-model="form.appletShowEnable"
            active-color="#13ce66"
            :active-value="1"
            inactive-color="#ff4949"
            :inactive-value="0">
          </el-switch>
        </el-form-item>
        <el-form-item label="活动开始时间" prop="beginTime">
          <el-date-picker
            :disabled="detailsType"
            v-model="form.beginTime"
            placeholder="请输入活动开始时间"
            value-format="timestamp"
            type="datetime">
          </el-date-picker>
        </el-form-item>
        <!--        <el-form-item label="创建时间" prop="creatTime">
                  <el-input v-model="form.creatTime" placeholder="请输入创建时间"/>
                </el-form-item>-->
        <el-form-item label="活动结束时间" prop="endTime">
          <el-date-picker
            :disabled="detailsType"
            v-model="form.endTime"
            value-format="timestamp"
            placeholder="请输入活动结束时间"
            type="datetime">
          </el-date-picker>
          <!--
                    <el-input v-model="form.endTime" placeholder="请输入活动结束时间"/>
          -->
        </el-form-item>
        <el-form-item label="参与活动等级" prop="levelEnable">
          <el-select v-model="form.levelEnable" clearable placeholder="请选择参与活动等级" :disabled="detailsType">
            <el-option
              v-for="num in 5"
              :key="num"
              :label="num+'级'"
              :value="num"
            />
          </el-select>
          <!--          <el-input v-model="form.levelEnable" placeholder="请输入参与活动等级"/>-->
        </el-form-item>
        <el-form-item label="允许参与次数" prop="hitEnableCounts">
          <el-input-number v-model="form.hitEnableCounts" :min="0" controls-position="right" :disabled="detailsType"></el-input-number>
          <!--          <el-input v-model="form.hitEnableCounts" placeholder="请输入允许参与次数"/>-->
        </el-form-item>

        <el-form-item label="最大允许数" prop="maxChoose">
          <el-input-number v-model="form.maxChoose" :min="1" controls-position="right" :disabled="detailsType"></el-input-number>
          <!--          <el-input v-model="form.maxChoose" placeholder="请输入最多可选卡券数量,取值[1,最大有效关联卡券]"/>-->
        </el-form-item>
<!--        <el-form-item label="代理商" prop="platformAgentId">
          <el-select v-model="form.platformAgentId" clearable placeholder="请选择代理商" @change="getAllStation" :disabled="detailsType">
            <el-option
              v-for="dict in agentList"
              :key="dict.id"
              :label="dict.agentName"
              :value="dict.id"
            />
          </el-select>
          &lt;!&ndash;          <el-input v-model="form.platformAgentId" placeholder="请输入代理商ID"/>&ndash;&gt;
        </el-form-item>-->
        <el-form-item label="关联场站" prop="stationList">
          <el-select v-model="form.stationList" class="labelWidth" clearable collapse-tags :disabled="detailsType"
                     filterable
                     multiple
                     placeholder="请选择场站"
          >
            <el-option
              v-for="item in stationNewList"
              :key="item.id"
              :label="item.stationName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="卡券设置" prop="couponsList">
          <el-select v-model="form.couponsList" class="labelWidth" clearable collapse-tags :disabled="detailsType"
                     filterable
                     multiple
                     placeholder="请选择卡券"
          >
            <el-option
              v-for="item in couponsList"
              :key="item.id"
              :label="item.couponsName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <div style="width: 100%">
          <!--            <el-form-item label="使用说明" prop="descriptionList">
                        <el-input v-model="form.descriptionList" placeholder="请输入有效时间"/>
                      </el-form-item>-->
          <el-form-item
            v-for="(domain, index) in form.descriptionList"
            :key="domain.key"
            :label="'使用说明' + index"
            :prop="'descriptionList.' + index + '.value'"
            :rules="{
                  required: true, message: `使用说明${index}不能为空`, trigger: 'blur'
                }"
          >
            <div style="display: flex;align-items: flex-start">
              <el-input v-model="domain.value" style="width: 300px;margin-right: 5px" :disabled="detailsType"></el-input>
              <el-button style="display: inline-block" v-if="index>0" @click.prevent="removeDomain(domain)">删除</el-button>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button @click="addDomain">新增使用说明</el-button>
          </el-form-item>
        </div>
<!--        <el-form-item label="活动状态" prop="sustained">
          <el-input v-model="form.sustained" placeholder="请输入持续的0:不持续(限定时间)，1:持续的(不限定时间)"/>
        </el-form-item>-->
<!--        <el-form-item label="持续的0:不持续(限定时间)，1:持续的(不限定时间)" prop="sustained">
          <el-input v-model="form.sustained" placeholder="请输入持续的0:不持续(限定时间)，1:持续的(不限定时间)"/>
        </el-form-item>-->
<!--        <el-form-item label="活动规则" prop="description">
          <el-input v-model="form.description" placeholder="请输入活动规则"/>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCommercialActivity,
  getCommercialActivity,
  delCommercialActivity,
  addCommercialActivity,
  updateCommercialActivity
} from "@/api/business/commercialActivity";
import {getAgentAll} from "@/api/platform/agent";
import {getAllStationByAgentId} from "@/api/business/station";
import {findCouponsByAgentId} from "@/api/business/coupons";
import {stationInfoList} from "@/api/home";

//0:创建(未发布)1:发布(进行中)2:停止(暂停或结束)
const statusList = [
  {
    label: '创建',
    value: 0
  },
  {
    label: '发布',
    value: 1
  },
  {
    label: '停止',
    value: 2
  }
]
export default {
  name: "CommercialActivity",
  data() {
    return {
      statusList,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商业活动表格数据
      commercialActivityList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activityName: null,
        activityNickName: null,
        appletShowEnable: null,
        beginTime: null,
        creatTime: null,
        description: null,
        endTime: null,
        hitEnableCounts: null,
        levelEnable: null,
        maxChoose: null,
        platformAgentId: null,
        status: null,
        sustained: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        activityName: {required: true, message: '请填写活动名称'},
        activityNickName: {required: true, message: '请填写活动别名'},
      },
      agentList: [],
      stationNewList: [],
      couponsList :[],
      detailsType:false,
    };
  },
  created() {
    this.getList();
    this.getAgentAll()
    this.getAllStation()
  },
  methods: {
    removeDomain(item) {
      const index = this.form.descriptionList.indexOf(item)
      if (index !== -1) {
        this.form.descriptionList.splice(index, 1)
      }
    },
    addDomain() {
      this.form.descriptionList.push({
        value: '',
        key: Date.now()
      });
    },
    async getAllStation() {
      let res = await stationInfoList()
      this.stationNewList = res.data
      let res1 = await findCouponsByAgentId()
      this.couponsList = res1.data
    },
    async getAgentAll() {
      let res = await getAgentAll()
      this.agentList = res.rows
    },
    /** 查询商业活动列表 */
    getList() {
      this.loading = true;
      listCommercialActivity(this.queryParams).then(response => {
        this.commercialActivityList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        activityName: null,
        activityNickName: null,
        appletShowEnable: null,
        beginTime: null,
        creatTime: null,
        description: null,
        endTime: null,
        hitEnableCounts: null,
        levelEnable: null,
        maxChoose: null,
        stationList: null,
        platformAgentId: null,
        status: null,
        sustained: null,
        descriptionList: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      //新增初始化使用说明三条
      this.form.descriptionList = [[{
        value: '',
        key:0
      }], [{
        value: '',key:1
      }], [{
        value: '',key:2
      }]]
      this.open = true;
      this.detailsType = false
      this.title = "添加商业活动";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCommercialActivity(id).then(response => {
        this.form = response.data;
        const list = []
        JSON.parse(this.form.description).forEach((item,index)=>{
          list.push({value:item,key:index})
        })
        this.form.descriptionList = list
        this.getAllStation()
        this.detailsType = false
        this.open = true;
        this.title = "修改商业活动";
      });
    },
    /** 详情按钮操作 */
    handleDetails(row) {
      this.reset();
      const id = row.id || this.ids
      getCommercialActivity(id).then(response => {
        this.form = response.data;
        const list = []
        JSON.parse(this.form.description).forEach((item,index)=>{
          list.push({value:item,key:index})
        })
        this.getAllStation()
        this.detailsType = true
        this.open = true;
        this.title = "商业活动详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.descriptionList = this.form.descriptionList.map(({ value }) => value)
          if (this.form.id != null) {
            updateCommercialActivity(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCommercialActivity(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商业活动编号为"' + ids + '"的数据项？').then(function () {
        return delCommercialActivity(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('activitys/commercialActivity/export', {
        ...this.queryParams
      }, `commercialActivity_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
